
const Koa = require('koa');
const MongoClient = require('mongodb').MongoClient;
const proxySerce = require('./proxy');
const mysql = require('mysql');
const config = require('./app/config');
const init = require('./app/init');
const request = require('superagent');

const ip = '120.24.218.74:27017';
const port = '8080';
const waitForIP = ()=>{
    return new Promise(async (resolve, reject) => {
        process.stdout.write(`请输入当前IP:\n`);
        process.stdin.resume();
        process.stdin.setEncoding('utf-8');
        process.stdin.once('data', async (chunk) => {
            chunk = chunk.replace(/(\n|\r|\s)/g, '');
            if(chunk === ""){
                reject("输入了空的字符串")
            } else {
                resolve(chunk)
            }
        });
    });
};
MongoClient.connect(`mongodb://vino:3623@${ip}/proxy_serve`,{poolSize:1,autoReconnect:true}, async function (err, db) {
    if(err){
        console.error("proxy server error" , err)
    } else {
        const poolOfZhima = mysql.createPool({
            connectionLimit: 50,
            host: 'rm-bp17ycm69kh5qi7yyo.mysql.rds.aliyuncs.com',
            user: 'zhima_http',
            password: 'Pz1VF1oS4Z4VrItN',
            port: 3306,
            database: 'zhima_http',
            charset: 'UTF8_GENERAL_CI'
        });
        global.getSesameConnect = ()=>{
            return new Promise(function (resolve, reject) {
                poolOfZhima.getConnection(function(err, connection) {
                    if (err) reject('从数据连接池中获取连接失败:'+err.message);
                    resolve(connection);
                });
            });
        };
        global.mydb = db.db('proxy_serve');
        const app = new Koa();
        await init();
        let server = await config(app, mydb);
        // let ip = await waitForIP();
        // await proxySerce.startProxy("119.137.54.77");
        server.listen(port);
        console.error("proxy server start" , port)
    }
});